#if !(UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX || UNITY_STANDALONE_OSX || STEAMWORKS_WIN || STEAMWORKS_LIN_OSX)
#define DISABLESTEAMWORKS
#endif
using System;
using System.Threading.Tasks;
using UnityEngine;
#if !DISABLESTEAMWORKS
using Steamworks;
#endif
namespace Gj.Steam
{
    public class Steam:GameManager
    {
        public static Steam Instance;
        public static SteamSettings settings;
        public static bool init = false;

        public static bool In
        {
            // get { return !string.IsNullOrEmpty(AppId); }

            get
            {
#if !DISABLESTEAMWORKS
                return Steamworks.SteamAPI.IsSteamRunning();
#else
                return false;
#endif
            }
        }
        static Steam()
        {
            settings = LoadSettings();
            Instance = new Steam();
        }

        private static SteamSettings LoadSettings()
        {
            SteamSettings loadedSettings = (SteamSettings)Resources.Load("SteamSettings", typeof(SteamSettings));
            if (loadedSettings == null)
            {
                loadedSettings = ScriptableObject.CreateInstance<SteamSettings>();
                Debug.Log("SteamSettings is not exist (Resources)");
            }
            return loadedSettings;
        }
        public static void Init(ChannelInfo info)
        {
            if (!info.id.Contains("steam"))
            {
                Debug.Log("SteamSettings  channel is error:"+info.id);
                return;
            }
#if DISABLESTEAMWORKS
                Debug.Log("SteamSettings  distable");
            return;
#else
            AppId_t t = new AppId_t();
            t.m_AppId = Convert.ToUInt32(settings.AppId);
            if (Steamworks.SteamAPI.RestartAppIfNecessary(t))
            {
                Application.Quit();
                return;
            }
            Game.single.RegisterManager(Instance);
#endif
        }

        public void OnInit()
        {
#if !DISABLESTEAMWORKS
            Steamworks.Callback<GetTicketForWebApiResponse_t>.Create((res) =>
            {
                User.GetTicketForWebApiResponse(res);
            });
            SteamAPI.Init();
            init = true;
#endif
        }

        public async Task OnUpdate()
        {
#if !DISABLESTEAMWORKS
            if (init)
            {
                SteamAPI.RunCallbacks();
            }
#endif
        }

        public void OnDestroy()
        {
#if !DISABLESTEAMWORKS
            if (!init) return;
            SteamAPI.Shutdown();
#endif
        }

        public void OnPage(BasePage page)
        {
        }
    }
}